﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace app
{
    class Program
    {
        #region Params

        

        #endregion

        internal static IPEndPoint listenEndPoint = new IPEndPoint(IPAddress.Any, Parameters.port);

        internal static Peer localPeer;

        static void Main(string[] args)
        {
            Random r = new Random();

            Parameters.port = r.Next(10000, 60000);

            CreateLocalPeer();

            Console.WriteLine("w " +
                Convert.ToBase64String(localPeer.IPEndPoint.Address.GetAddressBytes().Concat(
                BitConverter.GetBytes(localPeer.IPEndPoint.Port)).ToArray()));

            LocalData.Load();

            Server.Start();

            Peers.Start();

            int exit = 0;

            while (true)
            {
                List<byte> bb = new List<byte>();

                string[] ss = Console.ReadLine().Split(' ');

                if (ss[0] == "w" && ss.Length == 2)
                {
                    Peers.GetPeer(ss[1]);

                    continue;
                }
                else if(ss[0] == "#")
                {
                    if (ss.Length == 2)
                    {
                        Parameters.jumps = Convert.ToByte(ss[1]);

                        Parameters.secure = true;
                    }
                    else
                    {
                        Parameters.secure = false;

                        Parameters.jumps = 0;
                    }

                    continue;
                }

                foreach (string s in ss)
                {
                    if (s == "")
                        continue;

                    else bb.Add(Convert.ToByte(s));
                }

                if (bb.Count() == 0 && exit == 0)
                {
                    Peers.LoadPeersFromFile();
                    Console.WriteLine("Refreshing peers");
                    exit++;
                    continue;
                }
                else if (bb.Count() == 0 && exit == 1)
                    break;

                exit = 0;

                Peers.Send(bb.ToArray());
            }

            Server.Stop();
        }

        private static void CreateLocalPeer()
        {
            Random r = new Random();

            byte[] addr = new byte[Parameters.addressSize];
            
            r.NextBytes(addr);

            while(Convert.ToBase64String(addr).Split(Path.GetInvalidPathChars()).Length > 1)
                r.NextBytes(addr);

            localPeer = new Peer(addr, new IPEndPoint(IPAddress.Loopback, Parameters.port));

            Log.Add("LocalPeer", localPeer, new byte[0]);
        }

    }
}

